package com.ysh.smartplatform.controller;



import com.ysh.smartplatform.dto.R;
import com.ysh.smartplatform.pojo.BaseUser;
import com.ysh.smartplatform.pojo.Menu;
import com.ysh.smartplatform.pojo.Role;
import com.ysh.smartplatform.service.MenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by jackiechan on 2021/02/7 23:51
 *
 * @author jackiechan
 */
@RestController
@Api(tags = "菜单管理模块" )
@RequestMapping("/menus")
public class MenuController {

    private MenuService menuService;

    @Autowired
    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
    }

    @GetMapping("/menus")
    @ApiOperation("查询当前用户所有菜单")
    public R getAllMenu() {
        //获取到用户的角色
        List<Role> roleList = ((BaseUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getRoleList();
        Set<Menu> menuSet = new HashSet<>();
        roleList.forEach(role -> {
            List<Menu> menuList = role.getMenuList();
            menuList.forEach(menu -> {
                if (menu.getMenuType().equalsIgnoreCase("M")) {
                    menuSet.add(menu);
                }

            });
        });
        return R.OK(menuSet);
    }


    @GetMapping("/menus/list")
    @ApiOperation("所有菜单")
    public R getAllMenuList() {
        List<Menu> allMenus = menuService.findAllMenus();
        return R.OK(allMenus);
    }



    @GetMapping("/menu/{id}")
    public R getMenuById(@PathVariable Long id) {
        return R.OK(menuService.getMenuById(id));
    }

    @PostMapping("/menu")
    public R updateMenu(@RequestBody Menu menu) {
        menuService.updateMenu(menu);
        return R.OK();
    }

    @DeleteMapping("/mmenu/{id}")
    public R deleteById(@PathVariable  Long id){
        menuService.deleteById(id);
        return R.OK();
    }
}
